package com.currentbp.Interesting.other;

import com.currentbp.common.entity.LinkNode;
import com.currentbp.util.all.StringUtil;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author baopan
 * @createTime 2024-03-11 14:18:15
 */
public class EachNFlip {
    /*
      每N个数字就反转

     解题思路：
     1、生成一个小的连接
     2、入参：
     3、返回值：{第N+1的节点，新连接的头节点}

     */
    @Test
    public void t1() {
        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7};
        flip(new int[]{1, 2, 3, 4, 5, 6, 7}, 3);
        StringUtil.printObject(arr);
    }

    private void flip(int[] arr, int n) {
        for (int i = 0; i < arr.length; ) {
            flipSome(arr, i, i + n - 1);
            i = i + n;
        }
    }

    private void flipSome(int[] arr, int start, int end) {
        if (end > arr.length) {
            end = arr.length - 1;
        }
        while (start != end) {
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }


    @Test
    public void t2() {
        StringUtil.printObject(flipLink(new LinkNode(new int[]{1, 2, 3, 4, 5, 6, 7}), 3).toString());
    }

    private LinkNode flipLink(LinkNode head, int n) {
        LinkNode newHead = new LinkNode();
        LinkNode newHead2 = newHead;
        while(true){
            LinkNode[] linkNodes = doEachFlipLink(head, n);
            LinkNode newLittleHead = linkNodes[0];
            LinkNode nextHead = linkNodes[1];
            LinkNode tailNode = linkNodes[2];

            newHead2.next=newLittleHead;
            newHead2 = tailNode;
            head = nextHead;

            if(nextHead == null){
                break;
            }
        }

        return newHead.next;
    }

    private LinkNode[] doEachFlipLink(LinkNode head, int n) {
        //第一个元素是新的节点的开始，第二个元素是剩余元素的开始，第三个元素是该链表的最后一个元素
        LinkNode[] result = new LinkNode[3];
        if (head == null) {
            return result;
        }
        LinkNode newHead = new LinkNode();
        LinkNode currentNode = head;
        LinkNode beforeNode = null;
        LinkNode tailNode = null;
        int temp = 1;
        while (currentNode != null && temp <= n) {
            if(temp==1){
                tailNode = currentNode;
            }
            beforeNode = currentNode;
            currentNode = currentNode.next;
            beforeNode.next = newHead.next;
            newHead.next = beforeNode;
            temp++;
        }

        result[0] = newHead.next;
        result[1] = currentNode;
        result[2] = tailNode;
        return result;
    }
}
